package com.gamefx.engine1.display
{
	import com.gamefx.resource.SWFLoader;
	import com.gamefx.resource.events.LoaderEvent;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.utils.ByteArray;

	[Event(name="parseComplete", type="com.gamefx.resource.events.LoaderEvent")]

	
	public class BMFLoader extends SWFLoader
	{
		public function BMFLoader(urlOrRequest:*, priority:uint = 1, estimatedBytes:uint = 0)
		{
			super(urlOrRequest, priority, estimatedBytes);
		}


		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------


		private var _data:BitmapClipData;

		public function get data():BitmapClipData
		{
			return _data;
		}


		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------

		override public function load():void
		{
			super.load();
		}


		/**
		 * 如果经过BMFBuilder处理过，读取文件头信息
		 * @param event
		 * @param bytes
		 */
		override protected function onDataComplete(event:Event, bytes:ByteArray):void
		{
			_data = new BitmapClipData();
			_data.url = url;

			var sHead:String = bytes.readUTFBytes(3);
			if (sHead != "CWS" && sHead != "FWS")
			{
				BMFParser.readBMFInfo(bytes, _data);
			}

			super.onDataComplete(event, bytes);
		}


		override protected function loader_completeHandler(event:Event):void
		{
			var mc:MovieClip = content as MovieClip;

			while (mc.currentLabels.length == 0 && mc.totalFrames == 1)
			{
				mc = mc.getChildAt(0) as MovieClip;
				_data.offsetX += mc.x;
				_data.offsetY += mc.y;
			}

			_data.source = mc;
			_data.bitmaps = {};

			if (_data.labels == null)
			{
				BMFParser.createBMFInfo(_data);
				BMFParser.parse(_data, parseCompleteCallBack);
			}

			super.loader_completeHandler(event);
		}

		private function parseCompleteCallBack():void
		{
			dispatchEvent(new LoaderEvent(LoaderEvent.PARSE_COMPLETE, this));
		}


	}
}
